package com.yy.main.app.web;

import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.util.MapUtil;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.yy.kit.annotation.HasPers;
import com.yy.kit.array.YYArrayKits;
import com.yy.kit.collections.YYMapKits;
import com.yy.kit.string.YYStrKits;
import com.yy.main.app.mapper.TQuestionsMapper;
import com.yy.main.app.web.base.CommonController;
import com.yy.pojo.base.TQuestions;
import com.yy.pojo.base.TQuestionsExample;
import com.yy.pojo.base.TUser;
import io.shardingjdbc.core.keygen.DefaultKeyGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 试题管理 前端控制器
 * </p>
 *
 * @author 杨阳
 * @since 2017年12月4日
 */
@Controller
@RequestMapping("/questions")
@Api(description = "试题管理前端控制器", tags = {"试题管理控制器"})
public class QuestionsController extends CommonController {

    @Autowired
    private TQuestionsMapper tQuestionsMapper;

    /**
     * <p>
     * 跳转到试题管理页面
     * </p>
     *
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年12月4日
     */
    @ApiOperation(value = "跳转到试题管理页面", httpMethod = "GET", notes = "跳转到试题管理页面")
    @RequestMapping(value = "/questionsList")
    @HasPers(name = "questions:manager")
    public ModelAndView goQuestionsPage(HttpServletRequest request) {
        TUser user = getCurrentUser(request.getSession());
        return goToPageByModelAndView("system/questions/questions_list", null, user.getId());
    }

    /**
     * <p>
     * 加载后台管理，试题管理的数据表格
     * </p>
     *
     * @param page    当前页数
     * @param limit   每页显示记录数
     * @param content 试题题干
     * @return {@link HashMap}
     * @author 杨阳
     * @since 2017年12月4日
     */
    @ApiOperation(value = "试题数据表格", httpMethod = "GET", notes = "加载后台管理，试题管理的数据表格")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页显示记录数", paramType = "query"),
            @ApiImplicitParam(name = "content", value = "试题题干", paramType = "query")
    })
    @RequestMapping(value = "/questionsTable", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> questionsTable(Integer page, Integer limit, String content) {
        TQuestionsExample example = new TQuestionsExample();
        TQuestionsExample.Criteria criteria = example.createCriteria();

        if (YYStrKits.isNotBlank(content)) {
            criteria.andContentLike(YYStrKits.like(content));
        }

        PageHelper.startPage(page, limit);
        List<TQuestions> questionList = tQuestionsMapper.selectByExample(example);
        return super.pageToMap(new PageInfo(questionList));
    }

    /**
     * <p>
     * 跳转到编辑试题的页面
     * </p>
     *
     * @param id 试题ID
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年12月4日
     */
    @ApiOperation(value = "跳转到编辑试题的页面", httpMethod = "GET",
            notes = "增加与修改为一个页面，用户必须包含questions:add,questions:update权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试题ID，如果是增加则为-1", required = true, paramType = "path")
    })
    @RequestMapping("/questionsform/{id}")
    @HasPers(name = "questions:add,questions:update")
    public ModelAndView goQuestionsForm(@PathVariable("id") long id, HttpServletRequest request) {
        TUser user = getCurrentUser(request.getSession());
        // 如果是新增id肯定是-1
        TQuestions questions = tQuestionsMapper.selectByPrimaryKey(id);
        if (null == questions) {
            questions = new TQuestions();
            questions.setId(-1L);
        }
        Map<String, Object> param = YYMapKits.createHashMap();
        param.put("questions", questions);
        return goToPageByModelAndView("system/questions/questions_form", param, user.getId());
    }

    /**
     * <p>
     * 查看试题详情
     * </p>
     *
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年12月4日
     */
    @ApiOperation(value = "查看试题详情", httpMethod = "GET", notes = "用户必须包含questions:show权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试题ID", required = true, paramType = "path")
    })
    @RequestMapping("/show/{id}")
    @HasPers(name = "questions:show")
    public ModelAndView show(@PathVariable("id") long id) {
        TQuestions questions = tQuestionsMapper.selectByPrimaryKey(id);
        Map<String, Object> param = YYMapKits.createHashMap();
        param.put("questions", questions);
        return goToPageByModelAndView("system/questions/questions_show", param);
    }

    /**
     * <p>
     * 保存试题信息
     * </p>
     *
     * @param questions 试题实体
     * @return {@link Map}
     * @author 杨阳
     * @since 2017年9月7日
     */
    @ApiOperation(value = "保存试题信息", httpMethod = "POST", notes = "用于修改或新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "questions", value = "试题实体类", required = true, paramType = "query")
    })
    @RequestMapping(value = "/savequestions", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> savequestions(TQuestions questions,
                                             HttpSession session, HttpServletRequest request) {
        Map<String, Object> result;

        if (questions.getId() == -1) {
            // 增加
            DefaultKeyGenerator generator = new DefaultKeyGenerator();
            Long id = generator.generateKey().longValue();

            questions.setId(id);
            questions.setCreate_date(new Date());
            Integer b = tQuestionsMapper.insert(questions);
            if (b > 0) {
                result = writeSuccess("增加试题成功!");
            } else {
                result = writeError("增加试题失败，请重试！");
            }
        } else {// 修改
            questions.setUpdate_date(new Date());
            Integer b = tQuestionsMapper.updateByPrimaryKeySelective(questions);
            if (b > 0) {
                result = writeSuccess("修改试题成功!");
            } else {
                result = writeError("修改试题失败，请重试！");
            }
        }
        return result;
    }

    /**
     * <p>
     * 删除试题
     * </p>
     *
     * @param id 试题ID
     * @return {@link Map}
     * @author 杨阳
     * @since 2017年12月4日
     */
    @ApiOperation(value = "删除试题", httpMethod = "POST", notes = "删除试题，用户需要拥有questions:delete权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试题ID", required = true, paramType = "path")
    })
    @RequestMapping("/delquestions/{id}")
    @HasPers(name = "questions:delete")
    @ResponseBody
    public Map<String, Object> delquestions(@PathVariable("id") long id) {
        Map<String, Object> map;
        Integer b = tQuestionsMapper.deleteByPrimaryKey(id);
        if (b > 0) {
            map = writeSuccess("删除成功!");
        } else {
            map = writeError("删除失败，请重试!");
        }
        return map;
    }
}
